package com.heima.gateway.app.filter;


import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Ordered 这是指定过滤器执行顺序的
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 全局过滤器的过滤方法,检验token是否合法
     *
     * @param exchange 交换机
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.1放行登录请求
        String path = request.getURI().getPath();
        if (StringUtils.contains(path, "/login/login_auth")) {
            return chain.filter(exchange);
        }
        
        //2.获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //没token返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //3.检验token
        Claims claims = AppJwtUtil.getClaimsBody(token);
        //比较token
        int i = AppJwtUtil.verifyToken(claims);
        if (i == 0 || i == -1) {
            //通过:放行
            return chain.filter(exchange);
        }
        //失败:返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
